package com.csjbot.blackgaga.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.azoft.carousellayoutmanager.CarouselLayoutManager;
import com.azoft.carousellayoutmanager.CarouselZoomPostLayoutListener;
import com.azoft.carousellayoutmanager.CenterScrollListener;
import com.csjbot.blackgaga.BuildConfig;
import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.ai.HomeAI;
import com.csjbot.blackgaga.base.BaseFullScreenActivity;
import com.csjbot.blackgaga.base.BasePresenter;
import com.csjbot.blackgaga.cart.entity.RobotMenuListBean;
import com.csjbot.blackgaga.core.RobotManager;
import com.csjbot.blackgaga.feature.aboutus.AboutUsActivity;
import com.csjbot.blackgaga.feature.navigation.NaviAction;
import com.csjbot.blackgaga.feature.navigation.NaviActivity;
import com.csjbot.blackgaga.feature.navigation.NaviGuideCommentActivity;
import com.csjbot.blackgaga.feature.nearbyservice.NearByActivity;
import com.csjbot.blackgaga.feature.vipcenter.VipCenterActivity;
import com.csjbot.blackgaga.global.Constants;
import com.csjbot.blackgaga.model.http.product.ProductProxy;
import com.csjbot.blackgaga.model.tcp.body_action.IAction;
import com.csjbot.blackgaga.model.tcp.chassis.IChassis;
import com.csjbot.blackgaga.model.tcp.factory.ServerFactory;
import com.csjbot.blackgaga.network.CheckEthernetService;
import com.csjbot.blackgaga.router.BRouter;
import com.csjbot.blackgaga.router.BRouterKey;
import com.csjbot.blackgaga.router.BRouterPath;
import com.csjbot.blackgaga.service.BatteryService;
import com.csjbot.blackgaga.service.HomeService;
import com.csjbot.blackgaga.speechrule.SpeechRule;
import com.csjbot.blackgaga.util.BlackgagaLogger;
import com.csjbot.blackgaga.util.SharedKey;
import com.csjbot.blackgaga.util.SharedPreUtil;
import com.csjbot.blackgaga.widget.NewRetailDialog;
import com.csjbot.coshandler.listener.OnFaceListener;
import com.csjbot.coshandler.listener.OnMapListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by jingwc on 2017/10/11.
 */

public class HomeActivity extends BaseFullScreenActivity {

    @BindView(R.id.home_recycler)
    RecyclerView mRecyclerView;

    @BindView(R.id.language)
    LinearLayout mLanguage;

    HomeAdapter mAdapter;

    CarouselLayoutManager mLayoutManager;

    Class<? extends Activity> actClass;

    private OnMapListener listener;

    HomeAI mHomeAI;

    boolean isWelcome;

    int centerIndex = 0;

    volatile boolean isDetected;

    volatile boolean isComplete;

    boolean isNetworkEmptyData;

    private IChassis chassis;

    private boolean isFinish = false;
    private boolean isLoadMapSuccess;

    @Override
    public void afterViewCreated(Bundle savedInstanceState) {
        super.afterViewCreated(savedInstanceState);

        readLocalLanguage();
        startHomeService();
        startService(new Intent(this, CheckEthernetService.class));
        loadData();

        new Handler().postDelayed(()->startService(new Intent(HomeActivity.this,BatteryService.class)),1000);

    }

    private void readLocalLanguage() {
        Constants.Language.CURRENT_LANGUAGE =
                SharedPreUtil.
                        getInt(SharedKey.LANGUAGEMODE_NAME
                                , SharedKey.LANGUAGEMODE_KEY
                                , Constants.Language.CHINESE);
    }

    private void startHomeService() {
        HomeService.IS_SWITCH_LANGUAGE = true;
        /* 启动控制底层连接的HomeService */
        startService(new Intent(this, HomeService.class));
    }

    private void loadData() {
        ProductProxy proxy = com.csjbot.blackgaga.model.http.factory.ServerFactory.createProduct();
        proxy.removeMenuList();
        proxy.getRobotMenuList(true);
    }

    List<RobotMenuListBean.ResultBean.MenulistBean> getDefaultMenu() {
        isNetworkEmptyData = true;
        List<RobotMenuListBean.ResultBean.MenulistBean> menus = new ArrayList<>();
        RobotMenuListBean.ResultBean.MenulistBean menu;

        menu = new RobotMenuListBean.ResultBean.MenulistBean();
        menu.setMenuName(getString(R.string.about));
        menu.setMImg(String.valueOf(R.drawable.iv_about));
        menus.add(menu);

        menu = new RobotMenuListBean.ResultBean.MenulistBean();
        menu.setMenuName(getString(R.string.vip_center));
        menu.setMImg(String.valueOf(R.drawable.iv_member_center));
        menus.add(menu);
        menu = new RobotMenuListBean.ResultBean.MenulistBean();
        menu.setMenuName(getString(R.string.nav));
        menu.setMImg(String.valueOf(R.drawable.iv_navigation));
        menus.add(menu);

        menu = new RobotMenuListBean.ResultBean.MenulistBean();
        menu.setMenuName(getString(R.string.local_service));
        menu.setMImg(String.valueOf(R.drawable.iv_peripheral_services));
        menus.add(menu);

        centerIndex = 1;
        return menus;
    }


    @Override
    public void init() {
        super.init();
        mLayoutManager = new CarouselLayoutManager(CarouselLayoutManager.HORIZONTAL, false);
        mLayoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener());
        mLayoutManager.setMaxVisibleItems(2);
        mLayoutManager.addOnItemSelectionListener(adapterPosition -> mLanguage.setVisibility(View.VISIBLE));

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter = new HomeAdapter(itemClickListener));
        mRecyclerView.addOnScrollListener(new CenterScrollListener());

        mHomeAI = HomeAI.newInstance();
        mHomeAI.initAI(this);

        addFaceListener();

        chassis = ServerFactory.getChassisInstance();
        RobotManager.getInstance().addListener(new OnMapListener() {
            @Override
            public void saveMap(boolean state) {

            }

            @Override
            public void loadMap(boolean state) {
                restoreMapResult(state);
            }
        });
        mAdapter.addAll(getDefaultMenu());
        mLayoutManager.scrollToPosition(centerIndex);
        NaviAction.getInstance().setNaviActionListener(current -> runOnUiThread(() -> {
            if (current != null) {
                speak(current.getName() + "已经带到，我要回去了，如需要其他帮助请去找我，谢谢。");
                startActivity(new Intent(HomeActivity.this, NaviGuideCommentActivity.class));
            }
        }));

        listener = new OnMapListener() {
            @Override
            public void saveMap(boolean state) {}

            @Override
            public void loadMap(boolean state) {
                restoreMapResult(state);
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();

        isWelcome = true;
        isLoadMapSuccess = SharedPreUtil.getBoolean(SharedKey.ISLOADMAP, SharedKey.ISLOADMAP,false);
        NaviAction.getInstance().setPositionListener();

        RobotManager.getInstance().addListener(listener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isWelcome = false;
    }

    void addFaceListener() {
        /* 添加检测人脸监听 */
        RobotManager.getInstance().addListener(new OnFaceListener() {
            @Override
            public void personInfo(String json) {
                if (isDetected && isWelcome && !isComplete) {
                    try {
                        JSONObject jsonObject = (JSONObject) new JSONObject(json).getJSONArray("face_list").get(0);
                        JSONObject faceRecg = jsonObject.getJSONObject("face_recg");
                        int confidence = faceRecg.getInt("confidence");
                        String name = faceRecg.getString("name");
                        if (confidence > 80) {
                            welcomeAction();
                            isComplete = true;
                            String text = getString(R.string.hello) + "," + name + "," + getString(R.string.welcome);
                            getLog().debug("class:HomeActivity message:" + text);
                            speak(text);
                            runOnUiThread(() -> setRobotChatMsg(text));
                        }
                    } catch (JSONException e) {
                        getLog().error("class:HomeActivity e:" + e.toString());
                    }
                }
            }

            @Override
            public void personNear(boolean person) {
                Constants.Face.person = person;
                isDetected = person;
                if (person) {
                    isComplete = false;
                    new Thread(() -> {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            getLog().debug("class:HomeActivity error:" + e.toString());
                        }
                        if (!isComplete && isWelcome) {
                            isComplete = true;
                            welcome();
                            welcomeAction();
                        }

                    }).start();
                }
            }

            @Override
            public void personList(String json) {

            }
        });
    }

    public void welcome() {
        String text = getString(R.string.hello_welcome);
        runOnUiThread(() -> setRobotChatMsg(text));
        speak(text);
    }

    public void welcomeAction() {
        new Thread(() -> {
            IAction action = ServerFactory.getActionInstance();
            switch (BuildConfig.robotType) {
                case BuildConfig.ROBOT_TYPE_DEF_ALICE:
                    action.righLargeArmUp();
                    action.nodAction();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    action.rightLargeArmDown();
                    break;
                case BuildConfig.ROBOT_TYPE_DEF_SNOW:
                    action.snowDoubleArm();
                    break;
            }

        }).start();

    }


    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void itemClick(int position) {
            boolean isDelayed = false;
            actClass = null;
            if (position != mLayoutManager.getCenterItemPosition()) {
                mLayoutManager.smoothScrollToPosition(mRecyclerView, null, position);
                isDelayed = true;
            }
            RobotMenuListBean.ResultBean.MenulistBean menu = mAdapter.datas.get(position);

            String name = menu.getMenuName();

            if (name.equals(getString(R.string.nav))) {
                BlackgagaLogger.debug("isloadMap" + isLoadMapSuccess);
                if (!isLoadMapSuccess) {
                    restoreMapDialog();
                } else {
                    actClass = NaviActivity.class;
                }
            } else if (name.equals(getString(R.string.local_service))) {
                actClass = NearByActivity.class;
            } else if (name.equals(getString(R.string.vip_center))) {
                actClass = VipCenterActivity.class;
            } else if (name.equals(getString(R.string.about))) {
                actClass = AboutUsActivity.class;
            }
            if (actClass != null && isDelayed) {
                new Handler().postDelayed(() -> jumpActivity(actClass), 500);
            } else {
                jumpActivity(actClass);
            }
        }
    };

    @OnClick(R.id.iv_right)
    public void next() {
        int centerPosition = mLayoutManager.getCenterItemPosition();
        if (centerPosition == mAdapter.datas.size() - 1) {
            return;
        }
        mLayoutManager.smoothScrollToPosition(mRecyclerView, null, mLayoutManager.getCenterItemPosition() + 1);
    }

    @OnClick(R.id.iv_left)
    public void prev() {
        int centerPosition = mLayoutManager.getCenterItemPosition();
        if (centerPosition == 0) {
            return;
        }
        mLayoutManager.smoothScrollToPosition(mRecyclerView, null, mLayoutManager.getCenterItemPosition() - 1);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    public boolean isOpenTitle() {
        return true;
    }

    @Override
    public boolean isOpenChat() {
        return true;
    }

    interface OnItemClickListener {
        void itemClick(int position);
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

        List<RobotMenuListBean.ResultBean.MenulistBean> datas;

        OnItemClickListener listener;

        HomeAdapter(OnItemClickListener listener) {
            super();
            this.datas = new ArrayList<>();
            this.listener = listener;
        }

        void addAll(List<RobotMenuListBean.ResultBean.MenulistBean> datas) {
            this.datas.clear();
            this.datas.addAll(datas);
            this.notifyDataSetChanged();
            BlackgagaLogger.debug("isNetworkEmptyData:" + isNetworkEmptyData);
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(LayoutInflater.from(
                    HomeActivity.this).inflate(R.layout.item_home_list, parent,
                    false));
        }


        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            RobotMenuListBean.ResultBean.MenulistBean menu = datas.get(position);
            holder.iv.setImageResource(Integer.valueOf(menu.getMImg()));
            holder.tv.setText(menu.getMenuName());
            holder.iv.setOnClickListener(v -> {
                if (listener != null) {
                    listener.itemClick(holder.getAdapterPosition());
                }
            });
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            ImageView iv;

            TextView tv;

            MyViewHolder(View view) {
                super(view);
                iv = view.findViewById(R.id.iv);
                tv = view.findViewById(R.id.tv);
            }
        }

    }

    @Override
    protected boolean onSpeechMessage(String text, String answerText) {
        // 拦截主页的语音控制返回动作
        getChatControl().addIntercept(this.getClass().getSimpleName(), SpeechRule.Action.BACK, null);
        // 拦截主页的语音控制返回主页动作
        getChatControl().addIntercept(this.getClass().getSimpleName(), SpeechRule.Action.GO, this.getClass().getSimpleName());

        if(super.onSpeechMessage(text, answerText)){
            return false;
        }

        prattle(answerText);
        return true;
    }

    public void goVIPCenterAct() {
        jumpActivity(VipCenterActivity.class);
    }


    public void goNaviActAI() {
        if (!isLoadMapSuccess) {
            restoreMapDialog();
        } else {
            BRouter.getInstance()
                    .build(BRouterPath.NAVI_MAIN)
                    .withBoolean(BRouterKey.NO_POINT_GUIDE, true)
                    .navigation();
        }
    }

    public void goNearByAct() {
        jumpActivity(NearByActivity.class);
    }

    /* 恢复地图对话框 */
    private void restoreMapDialog() {
        if (RobotManager.getInstance().getConnectState() && !isLoadMapSuccess) {
            showNewRetailDialog(getString(R.string.map_manager), getString(R.string.is_restore_map), new NewRetailDialog.OnDialogClickListener() {
                @Override
                public void yes() {
                    loadmap();
                    dismissNewRetailDialog();
                }

                @Override
                public void no() {
                    dismissNewRetailDialog();
                }
            });
        } else {
            Toast.makeText(context, R.string.not_connect_slam, Toast.LENGTH_SHORT).show();
        }
    }

    private void loadmap() {
        chassis.loadMap();
        isFinish = false;
        checkConnect();
    }

    private void checkConnect() {
        mRecyclerView.postDelayed(() -> runOnUiThread(() -> {
            if (!isFinish) {
                Toast.makeText(HomeActivity.this, R.string.check_linux, Toast.LENGTH_SHORT).show();
            }
        }), Constants.internalCheckLinux);
    }

    private void restoreMapResult(boolean isState) {
        runOnUiThread(() -> {
            isFinish = true;
            if (isState) {
                isLoadMapSuccess = true;
                SharedPreUtil.putBoolean(SharedKey.ISLOADMAP, SharedKey.ISLOADMAP, true);
                Toast.makeText(HomeActivity.this, R.string.restore_map_success, Toast.LENGTH_LONG).show();
                jumpActivity(NaviActivity.class);
            } else {
                Toast.makeText(HomeActivity.this, R.string.restore_map_fail, Toast.LENGTH_LONG).show();
            }
        });
    }

}
